const { Sequelize } = require('sequelize')
const changeCase = require('change-case')
const path = require('path')
const fs = require('fs')
const sequelizePaginate = require('sequelize-paginate')
const loadModels = (sequelize) => {
  const root = path.resolve(__dirname, './models')
  const models = {}

  fs.readdirSync(root).forEach((filename) => {
    const modelName = changeCase.pascalCase(filename.replace('.js', ''))
    const filepath = path.resolve(root, filename)
    const model = require(filepath)(sequelize, models)
    sequelizePaginate.paginate(model)

    models[modelName] = model
  })

  // 关联
  Object.keys(models).forEach((key) => {
    const model = models[key]
    if (model.associate) {
      model.associate(models)
    }
  })

  return models
}

module.exports = ({ logger, config }) => {
  const { url } = config.get('database')
  const log = (message) => {
    logger.info(`[MySQL Client]：${message}`)
  }
  const sequelize = new Sequelize(url, {
    timezone: '+08:00',
    logging: log,
    dialect: 'mysql',
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000,
    },
    hooks: {
      beforeDestroy(data, options) {
        console.log(data)
      },
    },
    define: {
      underscored: true,
      paranoid: true,
    },
  })

  const models = loadModels(sequelize)

  return {
    sequelize,
    models,
    connect: async () => {
      log(`正在链接数据库：${url}`)
      await sequelize.authenticate()
      log(`数据库链接成功`)
    },
  }
}
